const sip = require("sip");
const digest = require("sip/digest");
const deviceCache = require("../../../db/deviceCache");
const config = require("../../../db/config");
const settingModel = require("../../../model/setting");

/**
 * 回应心跳信令，如果设备未注册发送 Unauthorized
 * @param {*} rq
 */
module.exports = {

    generate(rq) {
        const rs = sip.makeResponse(rq, 200, 'OK');
        const deviceId = sip.parseUri(rq.headers.from.uri).user;
        if (!deviceCache.registry[deviceId]) {
            let userinfo = {username: deviceId};
            userinfo.session = userinfo.session || {realm: settingModel.cache.server_realm};
            let ret = digest.challenge(userinfo.session, sip.makeResponse(rq, 401, 'Unauthorized'));
            sip.send(ret);
        } else {
            deviceCache.registry[deviceId].online = true;
            deviceCache.registry[deviceId].last = (new Date()).getTime();
        }
        return rs;
    }
}
